<template>
  <a-card :body-style="{ height: height + 'px', padding: '10px' }">
    <div v-loading="loading">
      <a-tree
        :tree-data="treeData"
        default-expand-all
        show-line
        v-model:expanded-keys="expandedKeys"
        v-model:selected-keys="selectedKeys"
        :field-names="{
          children: 'children',
          title: 'name',
          key: 'id',
        }"
        @select="onSelect"
      >
        <template #title="{ name }">
          <span>{{ name }}</span>
        </template>
      </a-tree>
    </div>
  </a-card>
</template>
<script>
  import { defineComponent } from 'vue';
  import * as api from '@/api/base-data/product/category';

  export default defineComponent({
    components: {},
    props: {
      height: {
        type: Number,
        default: 100,
      },
      categoryTypes: {
        type: String,
        required: true,
      },
    },
    data() {
      return {
        loading: false,
        treeData: [
          {
            id: 0,
            name: '全部分类',
            children: [],
          },
        ],
        expandedKeys: [0],
        selectedKeys: [],
        id: '',
      };
    },
    created() {
      this.doSearch();
    },
    methods: {
      doSearch() {
        this.loading = true;
        api
          .selector({
            available: true,
            categoryTypes: this.categoryTypes,
          })
          .then((res) => {
            this.expandedKeys = [0, ...res.map((item) => item.id)];
            res = this.$utils.toArrayTree(res, {
              key: 'id',
              parentKey: 'parentId',
              children: 'children',
              strict: true,
            });
            this.treeData[0].children = [
              ...res.map((item) => Object.assign({ parentId: 0 }, item)),
            ];
          })
          .finally(() => {
            this.loading = false;
          });
      },
      onSelect(keys) {
        this.$emit('change', keys[0]);
      },
    },
  });
</script>
